<template>
  <div class="main">
    <!-- 查询区域 -->
    <div class="search">
      <el-form
        :model="searchForm"
        :rules="searchFormRules"
        ref="searchForm"
        size="small"
      >
        <el-form-item label="关键词" label-width="80px" prop="keywords">
          <el-input 
          placeholder="请输入关键词" 
          v-model="searchForm.keywords" 
          size="mini"
          ></el-input>
        </el-form-item>
        <el-form-item label="关系层级" label-width="80px" prop="level">
          <el-select
            v-model="searchForm.level"
            placeholder="关系层级"
            size="mini"
          >
            <el-option label="1" value="1"></el-option>
            <el-option label="2" value="2"></el-option>
            <el-option label="3" value="3"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="节点总数" label-width="80px" prop="limit">
          <el-input
            v-model.number="searchForm.limit"
            placeholder="请输入节点总数"
            size="mini"
          ></el-input>
        </el-form-item>
        <el-form-item style="margin-top:30px">
          <el-button @click="search()" type="primary" size="mini" class="searchBtn">查询</el-button>
          <el-button @click="resetSearch()" size="mini" class="searchBtn resetBtn">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <!-- 右键删除菜单 -->
    <div class="deleteNodeMenu" @click="deleteNode" :style="{
      display: deleteNodeMenuVisible ? 'block' : 'none',
      left: deleteNodeX,
      top: deleteNodeY
      }"
    >
      删除
    </div>
    <!-- 右键新增节点 -->
    <div class="addNodeMenu" @click="addNodeBtn" :style="{
      display: addNodeMenuVisible ? 'block' : 'none',
      left: addNodeX,
      top: addNodeY
      }"
    >
      新增节点
    </div>
    <!-- 右侧编辑框 -->
    <div class="edit" id="edit" :style="{
      transform: editVisible ? 'translateX(0px)' : 'translateX(350px)',
      transition: 'all .3s'
    }">
      <div 
        :style="{
          width: '242px',
        }"
        >
        <el-table 
        :data="tableDate" 
        :show-header="false"  
        size="small"
        :max-height="tableHeight"
        >
          <el-table-column  prop="name" label="关系" width="90">
            <template slot-scope="scope">
              <el-input 
                placeholder="关系"
                size="mini" 
                :style="{width: '70px'}"
                v-model="scope.row.name"
                v-if="scope.row.inputVisible == true"
                @keyup.enter.native="handleInputConfirm(scope.row)"
                @blur="handleInputConfirm(scope.row)"
                >
              </el-input>
              <font v-else>{{scope.row.name}}</font>
            </template>
          </el-table-column>
          <el-table-column prop="value" label="实体" width="90">
            <template slot-scope="scope">
              <el-input 
                placeholder="实体"
                size="mini" 
                :style="{width: '70px'}"
                v-model="scope.row.value"
                required="required"
                v-if="scope.row.inputVisible == true"
                @keyup.enter.native="handleInputConfirm(scope.row)"
                @blur="handleInputConfirm(scope.row)"
                >
              </el-input>
              <font v-else>{{scope.row.value}}</font>
            </template>
          </el-table-column>
          <!-- 编辑按钮 -->
          <el-table-column label="操作" width="50">
             <template slot-scope="scope">
               <el-button
                type="text"
                @click="editBtn(scope.$index, scope.row)" 
                class="editColBtn">
                 <i class="el-icon-edit"></i>
               </el-button>
             </template>
          </el-table-column>          
        </el-table>
        <!-- 添加属性/关系 -->
        <el-button type="text" @click="addBtn" class="addBtn">
          <i class="el-icon-plus"></i>
          <font>添加{{info}}</font>
        </el-button>
        <!-- 隐藏编辑框 -->
        <el-button type="text" @click="cancelEdit" class="cancelEdit">
          <i class="el-icon-close"></i>
        </el-button>        
      </div>
    </div>
    <!-- 视图 -->
    <div
      class="visualization-select"
      ref="chart"
      id="chart"
    ></div>
    <!-- 取消节点属性编辑确认框 -->
    <el-dialog
      title="提示"
      :visible.sync="dialogVisible"
      width="30%"
      :before-close="handleClose"
      :showClose="false"
    >
      <span style="font-size: 19px">是否保留更改</span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">否</el-button>
        <el-button type="primary" @click="dialogVisible = false">是</el-button>
      </span>
    </el-dialog>  
    <!-- 新增节点的弹窗 -->
    <!-- 1 节点本身的属性 -->
    <!--  1.1 name 用户手动输入 -->
    <!--  1.2 type 可多选 支持创建不存在type -->
    <!-- 2 节点的关系 -->
    <!--  2.1 节点的前驱节点 可多选 不可创建 与前驱节点的关系 可多选 支持创建 -->
    <!--  2.2 节点的后继节点 可多选 不可创建 与后继节点的关系 可多选 支持创建 -->
    <b-modal
      v-model="addNodeModal"
      title="新增节点"
    >
      <!-- 弹框内容 -->
      <div class="add-dialogue dialogue">
        <div class="title"><div class="con">属性</div></div>
        <div class="form-line flex-sp-ar">
          <div class="label" style="font-size: 13px">节点名</div>
          <div class="form-item">
            <el-input
              style="font-size: 13px; width: 300px"
              placeholder="请输入节点名"
              size="small"
              v-model="newNode.name"
            ></el-input>
          </div>
        </div>
        <div class="form-line flex-sp-ar">
          <div class="label" style="font-size: 13px">类型(标签)</div>
          <div class="form-item">
            <el-select
              style="width: 300px"
              size="small"
              v-model="newNode.type"
              multiple
              filterable
              allow-create
              default-first-option
              @focus="remoteSearchNodeTypeList"
              :loading="selectLoading"
              placeholder="请选择(可多选，支持创建不存在标签)"
            >
              <el-option
                v-for="(item, $index) in searchNodeTypeList"
                :key="$index"
                :label="item"
                :value="item">
              </el-option>
            </el-select>
          </div>
        </div>
        <!-- 前驱节点列表 -->
        <div class="title" style="margin-top: 10px"><div class="con">前驱(可选)</div></div>
        <el-table
          size="mini"
          :data="newNode.prevNodeList"
          style="width: 100%"
          max-height="250">
          <el-table-column
            fixed
            prop="id"
            label="节点名"
          >
            <template slot-scope="scope">
              <el-select
                size="mini"
                v-model="scope.row.id"
                filterable
                remote
                reserve-keyword
                placeholder="关键词(不支持创建)"
                :remote-method="remoteSearchPreNodeList"
                :loading="selectLoading">
                <el-option
                  v-for="(item, $index) in searchPreNodeList"
                  :key="$index"
                  :label="item.name"
                  :value="item.id">
                </el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column
            prop="relationType"
            label="关系名"
            width="200"
          >
            <template slot-scope="scope">
              <el-select
                size="mini"
                collapse-tags
                v-model="scope.row.relationType"
                multiple
                filterable
                allow-create
                placeholder="关键词(支持创建关系)"
                @focus="remoteSearchRelationTypeList"
                :loading="selectLoading">
                <el-option
                  v-for="(item, $index) in searchRelationTypeList"
                  :key="$index"
                  :label="item"
                  :value="item">
                </el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column
            fixed="right"
            label="操作"
            width="80">
            <template slot="header" slot-scope="scope">
              <el-button
                size="small"
                type="text"
                @click.native.prevent="addNodeListRow(scope.$index, newNode.prevNodeList)"
              >新增</el-button>
            </template>
            <template slot-scope="scope">
              <el-button
                @click.native.prevent="deleteNodeListRow(scope.$index, newNode.prevNodeList)"
                type="text"
                size="small"
              >
                <span style="color: #f56c6c">移除</span>
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 后继 -->
        <div class="title" style="margin-top: 10px"><div class="con">后继(可选)</div></div>
        <el-table
          size="mini"
          :data="newNode.backNodeList"
          style="width: 100%"
          max-height="250">
          <el-table-column
            prop="id"
            label="节点名"
          >
            <template slot-scope="scope">
              <el-select
                size="mini"
                v-model="scope.row.id"
                filterable
                remote
                reserve-keyword
                placeholder="关键词(不支持创建)"
                :remote-method="remoteSearchBackNodeList"
                :loading="selectLoading">
                <el-option
                  v-for="(item, $index) in searchBackNodeList"
                  :key="$index"
                  :label="item.name"
                  :value="item.id">
                </el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column
            prop="relationType"
            label="关系名"
            width="200"
          >
            <template slot-scope="scope">
              <el-select
                size="mini"
                collapse-tags
                v-model="scope.row.relationType"
                multiple
                filterable
                allow-create
                placeholder="关键词(支持创建关系)"
                @focus="remoteSearchRelationTypeList"
                :loading="selectLoading">
                <el-option
                  v-for="(item, $index) in searchRelationTypeList"
                  :key="$index"
                  :label="item"
                  :value="item">
                </el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column
            fixed="right"
            label="操作"
            width="80">
            <template slot="header" slot-scope="scope">
              <el-button
                size="small"
                type="text"
                @click.native.prevent="addNodeListRow(scope.$index, newNode.backNodeList)"
              >新增</el-button>
            </template>
            <template slot-scope="scope">
              <el-button
                @click.native.prevent="deleteNodeListRow(scope.$index, newNode.backNodeList)"
                type="text"
                size="small"
              >
                <span style="color: #f56c6c">移除</span>
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <!-- 底部配置 -->
      <template slot="modal-footer">
        <div style="height: 40px; width: 40%" class="flex-right-center">
          <b-button
            variant="primary"
            @click="confirmAddNode"
            style="font-size: 14px; margin-right: 10px"
            size="sm"
          >确定</b-button>
          <b-button
            variant="outline-danger"
            @click="cancelAddNode"
            style="font-size: 14px"
            size="sm"
          >取消</b-button>
        </div>
      </template>
      <!-- 头部配置 -->
      <template slot="modal-header">
        <div class="header flex-left-center" style="font-size: 18px">新增节点</div>
      </template>
    </b-modal>
  </div>
</template>

<script>
import { getVisualData, getNodeInfo, getRelaInfo} from '@/api/visual'
import { delRelationList } from '@/api/relation'
import { addNode, deleteNodeList } from '@/api/node'
import { getRelationTypesV2, getNodeTypesV2 } from '@/api/type'

export default {
  data() {
    return {
      timer: null,
      chart: null,
      // 右侧编辑框
      editVisible: false,
      // 删除菜单是否显示
      deleteNodeMenuVisible: false,
      // 新增节点菜单是否显示
      addNodeMenuVisible: false,
      // 是否保留更改对话框是否显示
      dialogVisible: false,
      // 查询表单
      searchForm: {
        keywords: '桂林',
        level: 3,
        limit: 20
      },
      // 查询表单校验规则
      searchFormRules: {
        keywords: [{ required: false }],
        level: [{ required: true, message: '请选择关系层级', trigger: 'blur' }],
        limit: [
          { required: true, message: '请输入总节点数', trigger: 'blur' },
          { type: 'number', message: '请输入数字', trigger: 'blur' }
        ]
      },
      nodeList: [],
      linkList: [],
      // 节点数据
      tableDate: [], 
      // table高度自适应
      tableHeight: window.innerHeight - 200,
      // 删除菜单位置
      deleteNodeX: 0,
      deleteNodeY: 0,
      // 新增节点菜单位置
      addNodeX: 0,
      addNodeY: 0,
      allRela: [],
      relaList: [],
      // 添加属性/关系
      info: '',
      // 删除节点id
      delNodeId: '',
      // 节点是关系还是实体
      category: '',
      // 控制新增节点的弹框
      addNodeModal: false,
      // 新增的节点
      newNode: {
        name: '',
        type: [],
        prevNodeList: [],
        backNodeList: []
      },
      // 用于搜索选择的节点类型
      searchNodeTypeList: [],
      // 搜索框的局部loading
      selectLoading: false,
      // 用于搜索选择的前驱节点列表
      searchPreNodeList: [],
      // 用于搜索选择的关系列表
      searchRelationTypeList: [],   
      // 用于搜索选择的后继节点列表
      searchBackNodeList: [] 
    }
  },
  mounted () {
    // 全局点击事件
    document.getElementById('chart').onclick = e => {
        // 隐藏删除菜单
        this.deleteNodeMenuVisible = false
        // 隐藏新增节点菜单
        this.addNodeMenuVisible = false
        if (e.target.id === 'chart') {
        this.editVisible = false
      }
    }

    // 初始化
    this.chart = this.echarts.init(this.$refs.chart)
    this.chart.setOption(this.option)
    this.getData()

    // 阻止默认右击事件
    document.oncontextmenu = () => false

    // 右击节点/关系 删除
    this.chart.on('contextmenu', {dataType: 'node'}, (params) => {
      // 隐藏新增节点菜单  右击节点时，会触发右击空白处新增节点事件
      this.addNodeMenuVisible = false
      this.deleteNodeX = params.event.event.offsetX - 105 + 'px'
      this.deleteNodeY = params.event.event.offsetY - 45 + 'px'
      this.deleteNodeMenuVisible = true
      this.delNodeId = params.value
      this.category = params.data.category
    })
    
    // 点击节点
    this.chart.on('click', {dataType: 'node'}, (params) => {
      this.info = '关系'
      this.tableDate = []
      this.editVisible = true
      this.nodeInfo(params.value)
    })
    // 点击关系
    this.chart.on('click', {dataType: 'edge'}, (params) => {
      this.info = '关系'
      this.tableDate = []
      this.editVisible = true
      this.relaInfo(params.name)
      console.log(params.name)
    })

    // 右击空白处 新增
    document.getElementById('chart').onmouseup = (e) => {
      this.addNodeX = e.offsetX - 105 + 'px'
      this.addNodeY = e.offsetY - 45 + 'px'
      this.addNodeMenuVisible = true
    }
  },
  destroyed() {
    clearInterval(this.timer)
  },
  methods: {
    async getData () {
      this.loading = this.$loading({
        text: '正在查询图谱数据...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      const res = await getVisualData(this.searchForm)
      this.allRela = res.data
      console.log(res, '综合关系')
      // 取出所有节点ID（存在重复）
      const tpNodes = res.data.reduce((p, c) => {
        const node = c.nodes.map(n => {
          const tp = n.split('/')
          return parseInt(tp[tp.length - 1])
        })
        return p.concat(node)
      }, [])
      // 节点ID去重
      const nodeIds = Array.from(new Set(tpNodes))
      // 根据所有节点id，请求节点详情
      let promises = nodeIds.map(nodeId => getNodeInfo({ nodeId }))
      const nodeInfoResArr = await Promise.all(promises)
      // 获取所有节点列表
      this.nodeList = nodeInfoResArr.map(n => {
        return {
          ...n.data,
          symbolSize: 30,
          category: '实体'
        }
      })
      // 处理关系
      const tpRela = res.data.reduce((p, c) => {
        const rela = c.relationships.map(r => {
          const tp = r.split('/')
          return parseInt(tp[tp.length - 1])
        })
        return p.concat(rela)
      }, [])
      // 关系去重
      const relaIds = Array.from(new Set(tpRela))
      // 根据所有节点id，请求关系详情
      promises = relaIds.map(rid => getRelaInfo({ rid }))
      const relaInfoResArr = await Promise.all(promises)
      this.nodeList.push(
        ...relaInfoResArr.map(r => {
          return {
            ...r.data,
            symbolSize: 20,
            category: '关系'
          }
        })
      )   
      // 提取关系
      this.linkList = res.data.reduce((p, c) => {
        const links = []
        for (let i = 0; i < c.relationships.length; i++) {
          const pNodeArr = c.nodes[i].split('/')
          const rArr = c.relationships[i].split('/')
          const bNodeArr = c.nodes[i + 1].split('/')
          links.push({ source: '实体' + pNodeArr[pNodeArr.length - 1], target: '关系' + rArr[rArr.length - 1]})
          links.push({ source: '关系' + rArr[rArr.length - 1], target: '实体' + bNodeArr[bNodeArr.length - 1] })
        }
        return p.concat(links)
      }, [])
      console.log( this.linkList);
      this.loading.close()
      this.chart.setOption(this.option)
    },
    search () {
      this.$refs['searchForm'].validate(v => {
        if (!v) return false
        this.getData()
      })
    },
    // 点击节点
    async nodeInfo (nodeId) {
      let s = new Set()
      let relarr = new Array()
      let nodearr = new Array()
      // 节点对应的关系及实体
      this.relaList = this.allRela.reduce((p, c) => {
        const links = []
        for (let i = 0; i < c.relationships.length; i++) {
          const pNodeArr = c.nodes[i].split('/')
          if(parseInt(pNodeArr[pNodeArr.length - 1]) === nodeId) {
            const rArr = c.relationships[i].split('/')
            const bNodeArr = c.nodes[i + 1].split('/')
            if(!s.has(parseInt(rArr[rArr.length - 1]))) {
              s.add(parseInt(rArr[rArr.length - 1]))
              relarr.push({rid: parseInt(rArr[rArr.length - 1])})
              nodearr.push({nodeId: parseInt(bNodeArr[bNodeArr.length - 1])})
              links.push({rid: parseInt(rArr[rArr.length - 1]), nodeId: parseInt(bNodeArr[bNodeArr.length - 1])})
            }
          }
        }
        return p.concat(links)
      }, [])     
      for(let i = 0; i < relarr.length; i ++) {
        const relaData = await getRelaInfo(relarr[i])
        const nodeData = await getNodeInfo(nodearr[i])
        this.tableDate.push({name: relaData.data.name, value: nodeData.data.name, inputVisible: false})
      }
      console.log(this.tableDate)
    },
    // 点击边
    async relaInfo (str) {
      const tp = str.split(' > ')
      let rela = 0
      let node = 0
      if(tp[0].substring(0, 2) == '关系') {
        rela = parseInt(tp[0].substring(2))
        node = parseInt(tp[1].substring(2))
      }else {
        node = parseInt(tp[0].substring(2))
        rela = parseInt(tp[1].substring(2))
      }
      console.log('node', node);
      this.nodeInfo(node)
    },
    // 删除节点/关系
    deleteNode () {
      this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.loading = this.$loading({
          text: '正在删除...',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        })
        if(this.category == '实体') {
          deleteNodeList({ ids: [this.delNodeId] }).then(res => {
            this.loading.close()
            if (res.status === 'fail') {
              this.$message.warning(res.msg)
              return false
            }
            this.$message.success(res.msg)
            this.search()
          })
        } else {
          delRelationList({ ids: [this.delNodeId] }).then(res => {
            this.loading.close()
            if (res.status === 'fail') {
              this.$message.warning(res.msg)
              return false
            }
            this.$message.success(res.msg)
            this.search()
          })
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
      this.deleteNodeMenuVisible = false
    },

    // 查询重置
    resetSearch () {
      this.searchForm = {}
    },
    // 取消节点属性编辑
    cancelEdit () {
      this.editVisible = false
      this.dialogVisible = true
    },
    // 取消编辑确认框
    handleClose(done) {
      this.$confirm('确认关闭？')
        .then(_ => {
          done();
        })
        .catch(_ => {})
    },
    // 编辑指定属性，切换文本框
    editBtn (index, row) {
      row.inputVisible = true
      console.log(row);
    }, 
    // 文本框失去焦点或摁下了enter建触发
    handleInputConfirm (row) {
      if (row.name.trim().length != 0 && (row.value.trim().length != 0)) {
      row.inputVisible = false
      // 发起请求，保存操作
      this.saveEditNode(row)
      }
    },
    // 保存修改
    saveEditNode (row) {
      console.log(row)
      // this.$message({
      //   message: '修改成功',
      //   type: 'success'
      // })
    },    
    // 添加属性
    addBtn () {
      const lastData = this.tableDate[this.tableDate.length - 1]
      if (lastData && (lastData.name === '' || lastData.value === '')) {
        this.$message.warning('存在未填写表格')
        return false
      }
      const newdata = {
        name: '',
        value: '',
        inputVisible: true
      }
      this.tableDate.push(newdata)
    },
    // 添加节点
    addNodeBtn () {
      this.addNodeMenuVisible = false
      this.openAddNodeModal()
    },
    // 打开新增节点的弹窗
    openAddNodeModal () {
      this.currentOp = 'add'
      this.addNodeModal = true
      console.log('打开了新增节点的弹窗')
    },
    // 重置添加节点的表单
    resetAddNodeForm () {
      this.newNode = {
        name: '',
        type: [],
        prevNodeList: [],
        backNodeList: []
      }
    },
    // 确认新增节点
    confirmAddNode () {
      // 判断节点名是否为空
      if (this.newNode.name === '') {
        this.$message.warning('节点名不可以为空')
        return false
      }
      // 判断节点类型是否为空
      if (this.newNode.type.length === 0) {
        this.$message.warning('节点类型不可以为空')
        return false
      }
      // 如果前驱节点列表不为空 判断前驱节点列表的最后一个节点是否缺少信息
      if (this.newNode.prevNodeList.length !== 0) {
        const lastPreNode = this.newNode.prevNodeList[this.newNode.prevNodeList.length - 1]
        if (lastPreNode.id === '' || lastPreNode.relationType.length === 0) {
          this.$message.warning('前驱节点列表存在未填写内容')
          return false
        }
      }
      // 判断后继节点列表的最后一个节点是否缺少信息
      if (this.newNode.backNodeList.length !== 0) {
        const lastBackNode = this.newNode.backNodeList[this.newNode.backNodeList.length - 1]
        if (lastBackNode.id === '' || lastBackNode.relationType.length === 0) {
          this.$message.warning('后继节点列表存在未填写内容')
          return false
        }
      }
      console.log(this.newNode, 'new node')
      this.loading = this.$loading({
        text: '正在添加...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      addNode(this.newNode).then(res => {
        this.loading.close()
        console.log(res)
        if (res.status === 'success') {
          this.$message.success(res.msg)
        } else {
          this.$message.warning(res.msg)
        }
        this.cancelAddNode()
        this.search()
        this.resetAddNodeForm()
      })
    },
    addNodeListRow (_index, nodeList) {
      const lastNode = nodeList[nodeList.length - 1]
      if (lastNode && (lastNode.id === '' || lastNode.relationType.length === 0)) {
        this.$message.warning('存在未填写表格')
        return false
      }
      nodeList.push({
        id: '',
        relationType: []
      })
    },
    // 删除节点表格的行
    deleteNodeListRow (index, nodeList) {
      console.log('delete preNode list row')
      nodeList.splice(index, 1)
    },
    // 远程搜索节点类型列表下拉框
    remoteSearchNodeTypeList () {
      this.selectLoading = true
      getNodeTypesV2().then(res => {
        this.selectLoading = false
        if (res.status === 'fail') {
          this.$message.warning(res.msg)
          return false
        }
        this.searchNodeTypeList = res.data
      })
    },
    // 远程搜索关系类型列表下拉框
    remoteSearchRelationTypeList () {
      this.selectLoading = true
      getRelationTypesV2().then(res => {
        this.selectLoading = false
        if (res.status === 'fail') {
          this.$message.warning(res.msg)
          return false
        }
        this.searchRelationTypeList = res.data
      })
    },
    // 远程搜索前驱节点列表下拉框
    remoteSearchPreNodeList (query) {
      let reserve = this.newNode.prevNodeList.filter(node => node.id !== '')
      if (reserve.length !== 0) {
        reserve = reserve.map(node => {
          return {
            id: node.id,
            name: this.searchBackNodeList.filter(n => n.id === node.id)[0].name
          }
        })
      }
      if (query === '') {
        this.searchPreNodeList = [...reserve]
        return false
      }
      this.selectLoading = true
      // getNodeList({
      //   page: 1,
      //   records: this.searchTotalNodeCount,
      //   keywords: query,
      //   type: 'all'
      // }).then(res => {
      //   this.selectLoading = false
      //   this.searchPreNodeList = res.data.nodeList.map(item => {
      //     return {
      //       name: `${getLimitText(item.name, 20)}(${item.labels.join(',')})`,
      //       id: item._id
      //     }
      //   })
      //   // 过滤掉已经包含的
      //   const ids = this.searchPreNodeList.map(n => n.id)
      //   reserve = reserve.filter(n => !ids.includes(n.id))
      //   this.searchPreNodeList = this.searchPreNodeList.concat(reserve)
      // })
    },
    // 远程搜索后继节点列表下拉框
    remoteSearchBackNodeList (query) {
      let reserve = this.newNode.backNodeList.filter(node => node.id !== '')
      if (reserve.length !== 0) {
        reserve = reserve.map(node => {
          return {
            id: node.id,
            name: this.searchBackNodeList.filter(n => n.id === node.id)[0].name
          }
        })
      }
      if (query === '') {
        this.searchBackNodeList = [...reserve]
        return false
      }
      this.selectLoading = true
      // getNodeList({
      //   page: 1,
      //   records: 500,
      //   keywords: query,
      //   type: 'all'
      // }).then(res => {
      //   this.selectLoading = false
      //   console.log(res, 'remote')
      //   this.searchBackNodeList = res.data.nodeList.map(item => {
      //     return {
      //       name: `${getLimitText(item.name, 20)}(${item.labels.join(',')})`,
      //       id: item._id
      //     }
      //   })
      //   // 过滤掉已经包含的
      //   const ids = this.searchBackNodeList.map(n => n.id)
      //   reserve = reserve.filter(n => !ids.includes(n.id))
      //   console.log(reserve, '保留数组')
      //   this.searchBackNodeList = this.searchBackNodeList.concat(reserve)
      // })
    },
    // 取消新增节点
    cancelAddNode () {
      this.addNodeModal = false
    }
  },
  computed: {
    option () {
      return {
        backgroundColor: new this.echarts.graphic.RadialGradient(0.3, 0.3, 0.8, [
          {
            offset: 0,
            color: '#f7f8fa'
          },
          {
            offset: 1,
            color: '#cdd0d5'
          }
        ]),
        title: {
          text: '',
          subtext: '',
          right: 10,
          bottom: 10
        },
        layoutAnimation: false,
        tooltip: {},
        legend: [
          {
            formatter:  name => {
              return this.echarts.format.truncateText(
                name,
                80,
                '14px Microsoft Yahei',
                '…'
              )
            },
            tooltip: {
              show: true
            },
            selectedMode: 'false',
            bottom: 20,
            data: ['实体', '关系']
          }
        ],
        toolbox: {
          show: true,
          feature: {
            dataView: {
              show: true,
              readOnly: true
            },
            restore: {
              show: true
            },
            saveAsImage: {
              show: true
            }
          }
        },
        animationDuration: 100,
        series: [
          {
            name: '知识图谱',
            type: 'graph',
            layout: 'force',
            animation: false,
            force: {
              // 节点之间的斥力因子
              repulsion: 50,
              // 节点受到的向中心的引力因子
              gravity: 0.001,
              // 边的两个节点之间的距离
              edgeLength: 90,
              // 显示布局的迭代动画
              layoutAnimation: true,
              // 节点的移动速度
              friction: 0.6
            },
            data: this.nodeList.map((n, i) => {
              if (i === 0) {
                return {
                  ...n,
                  x: 0,
                  y: 0,
                  draggable: 'true',
                  value: n._id,
                  id: n.category + n._id
                }
              } else {
                return {
                  ...n,
                  value: n._id,
                  draggable: 'true',
                  id: n.category + n._id
                }
              }
            }),
            links: this.linkList,
            categories: [
              {
                name: '实体'
              },
              {
                name: '关系'
              }
            ],
            focusNodeAdjacency: true,
            roam: true,
            label: {
              normal: {
                show: true,
                position: 'top'
              }
            },
            lineStyle: {
              normal: {
                color: 'source',
                curveness: 0,
                type: 'solid'
              }
            }
          }
        ]
      }
    },
  }
}
</script>

<style lang="stylus" scoped>
.main
  width: 100%
  height: 100%
  position: relative

.visualization-select
  width: 100%
  height: calc(100% - 60px)

.search
  z-index: 999
  position: absolute
  height: 261px
  width: 238px
  background-color: rgba(0, 0, 0, 0.1)
  padding-top: 30px
  padding-right: 30px
  box-shadow: 2px 2px 10px #909090
  border-radius: 3px
  top 30px
  left 30px

.deleteNodeMenu
  z-index: 99999
  position: absolute
  width: 100px 
  height: 40px
  line-height: 32px
  font-size: 17px
  color: #424242
  background-color: #fff
  padding: 5px
  border-radius: 3px
  background-color: rgba(0, 0, 0, 0.2)
  box-shadow: 0px 0px 7px 1px #fff

.deleteNodeMenu:hover
  color: #F56C6C
  cursor: pointer

.addNodeMenu
  z-index: 99999
  position: absolute
  width: 100px 
  height: 40px
  line-height: 32px
  font-size: 17px
  color: #424242
  background-color: #fff
  padding: 5px
  border-radius: 3px
  background-color: rgba(0, 0, 0, 0.2)
  box-shadow: 0px 0px 7px 1px #fff

.addNodeMenu:hover
  color: #409EFF
  cursor: pointer

.searchBtn
  background: rgba(255, 251, 240, 0.3)
  background-color: #06a7ef38
  color: #068befc2
  outline: none

.edit
  z-index: 99999
  position: absolute
  height: calc(100% - 60px)
  width: 260px
  right: 0px
  padding: 30px 10px 20px 8px
  background-color #fff
  font-size: 12px
  background: rgba(0, 0, 0, 0.1)

.editCol
  position: relative

.editColBtn
  font-size: 19px

.cancelEdit
  position: absolute
  left: 0px
  top: -3px
  font-size: 18px

.addBtn
  position: absolute
  right: 20px
  margin-top: 10px
  font-size: 16px

.dialogue
  .title
    margin-bottom: 10px
    height: 20px
    width: 100%
    background-color: #409EFF
    box-sizing: border-box
    padding-left: 5px
    .con
      font-weight: 700
      width: 100%
      height: 100%
      background-color: #fff
      padding-left: 10px
      line-height: 19px

.table-node-type
  ::v-deep .el-input__inner
    max-width: 90px
    border 0
    color #F56C6C
    font-weight: 700
    font-size: 14px

/*最外层透明*/
/deep/ .el-table, /deep/ .el-table__expanded-cell
  background-color: transparent

/* 表格内背景颜色 */
/deep/ .el-table th,
/deep/ .el-table tr,
/deep/ .el-table td
  background-color: transparent

/*去每一行记录下的横线*/
.el-table--border tr,td
  border: none!important;

/* 删除表格下最底层的横线 */
.el-table::before
  left: 0
  bottom: 0
  width: 100%
  height: 0px

.el-table
  font-size: 14px
  // overflow: auto
  border-bottom 0
  // color hsla(0,0%,100%,.6)
  /* 设置滚动条的样式 */
  ::-webkit-scrollbar
    width 5px;/*滚动条粗细*/

  /* 滚动槽 */
  ::-webkit-scrollbar-track
    -webkit-box-shadow inset006pxrgba(0, 0, 0, 0.3)
    border-radius 10px

  /* 滚动条滑块 */
  ::-webkit-scrollbar-thumb
    border-radius 10px
    background rgba(0, 0, 0, 0.3)
    -webkit-box-shadow inset006pxrgba(0, 0, 0, 0.5)

.el-input /deep/ .el-input__inner {
    background-color: rgba(255, 255, 255, 0.7)
}
</style>
